<script setup lang="ts">
import { useResourceStore } from '@/stores/useResource'
const resourceStore = useResourceStore()
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

// 初始化默认值
const initData = () => ({
  name: '',
  categoryId: '',
  url: '',
  description: ''
})
const form = reactive(initData())

const isCreate = ref(true)
const msgText = ref('')
const iniAndShow = (id: number = 0) => {
  Object.assign(form, initData()) // 清空前表单数据
  dialogFormVisible.value = true
  isCreate.value = id ? true : false
  msgText.value = id ? '更新' : '新建'
  resourceStore.getAllResourcesCategory()
  if (id) {
    const editData = resourceStore.queryResult.records.find((item) => item.id == id)
    Object.assign(form, editData)
  }
}

const onSubmit = async () => {
  dialogFormVisible.value = false
  // 校验数据

  // 提交数据
  await resourceStore.saveOrUpdateResource(form)
  // 重新请求资源数据
  await resourceStore.queryResources()
}

// defineExpose()向外导出该方法，所有使用该组件的都可以调用该方法
defineExpose({ iniAndShow })
</script>
<template>
  <div class="dialog">
    <el-dialog v-model="dialogFormVisible" :title="msgText + '资源'">
      <el-form :model="form">
        <el-form-item label=" 资源名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label=" 资源路径" :label-width="formLabelWidth" prop="url">
          <el-input v-model="form.url" autocomplete="off" />
        </el-form-item>

        <el-form-item label="资源类别" :label-width="formLabelWidth" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="资源类别">
            <el-option label="不设置" value="" />
            <el-option :label="cate.name" :value="cate.id" v-for="cate in resourceStore.allResourcesCategory" :key="cate.id" />
          </el-select>
        </el-form-item>

        <el-form-item label=" 资源描述" :label-width="formLabelWidth" prop="description">
          <el-input type="textarea" v-model="form.description" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit"> 保存 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
.dialog {
  color: #000;
}

.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 200px;
}
.el-input {
  width: 700px;
}
.el-textarea {
  width: 750px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
